# enconding=utf-8
import ast
import jsonpath
from tools.opration_mysql import OprationMysql

class HandleAssert:

    def assert_response_value(self, check_list, response_dict):
        """

        :param check_str: 是一个列表形式的字符串
        :param response_dict: 接口响应数据，字典类型
        :return:
        """

        check_res = []
        # check_list = ast.literal_eval(check_str)

        for check in check_list:

            actual = jsonpath.jsonpath(response_dict, check["expr"])
            # print(response_dict,check['expr'])

            if isinstance(actual, list):
                actual = actual[0]
            # 与实际结果做比对
            if check["type"] == "eq":
                print(f"实际结果是{actual},预期结果是{check['expected']}")
                check_res.append(actual == check["expected"])
        print(f"断言结果列表是{check_res}")
        if False in check_res:
            # raise AssertionError
            print("部分断言失败")
            return False
        else:
            return True
        # return check_res
    def assert_db(self,check_list):
        """

        :param check_str:
        :return:
        """
        OM=OprationMysql()
        check_db_res=[]
        # check_list = ast.literal_eval(check_str)
        for check_db_dict in check_list:
            print(f"当前要比对的sql语句：{check_db_dict['sql']}")
            print(f"当前执行sql的查询类型为：{check_db_dict['db_type']}")
        if check_db_dict['db_type']=="count":
            print(f"比对数据库查询结果条数是否符合预期")
            res=OM.get_count(check_db_dict['sql'])
            print(f"sql的执行结果为：{res}，期望结果是：{check_db_dict['expected']}")
            check_db_res.append(res==check_db_dict['expected'])
        if False in check_db_res:
            print(f"部分断言失败，请查看数据库比对结果为False的数据")
            return False
        else:
            print(f"数据库断言成功")
            return True

if __name__ == '__main__':
    res = {"code": 0, "msg": "ok", "data": {"id": 1235, "reg_name": "u", "mobile_phone": "123141313"}}
    check_str = [{"expr": "$.code", "expected": 0, "type": "eq"},{"expr": "$.code", "expected": 0, "type": "eq"},{"expr": "$.code", "expected": 0, "type": "eq"}]
    print(HandleAssert().assert_response_value(check_str, res))
